<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello',
				connectedDevices: [], // 存储已连接设备
				currentDeviceId: '', // 当前连接设备ID
				characteristicId: '', // 特征值ID
				writedevices: null,
				deviceId: '',
				connected: '',
				writeCharacteristicsId: '',
				notifyCharacteristicsId: '',
			}
		},
		onLoad() {
			this.initBluetooth();
		},
		onUnload() {
			this.disconnect();
		},
		methods: {
			reconnectDevice() {
				this.reconnect();
			},
			// 1. 初始化蓝牙适配器
			initBluetooth() {
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log('蓝牙适配器初始化成功', res);
						this.startDiscovery();
					},
					fail: (err) => {
						console.error('初始化失败', err);
						if (err.errCode === 10001) {
							uni.showModal({
								title: '提示',
								content: '请开启手机蓝牙功能',
								showCancel: false
							});
						}
					}
				});
			},

			// 2. 开始搜索设备
			startDiscovery() {
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					success: (res) => {
						console.log('开始搜索设备', res);
						this.listenNewDevices();
					},
					fail: (err) => {
						console.error('搜索失败', err);
					}
				});
			},

			// 监听发现新设备
			listenNewDevices() {
				uni.onBluetoothDeviceFound((devices) => {
					console.log(devices);
					devices.devices.forEach(device => {
						if (device.name && device.name.includes('Bioland-BGM')) {
							console.log(device);
							console.log('发现目标设备', device);

							this.deviceId = device.deviceId;
							this.connectDevice(device.deviceId);
						}
					});
				});
			},

			// 3. 连接设备
			connectDevice(deviceId) {
				this.connectedDeviceId = deviceId;
				uni.createBLEConnection({
					deviceId: this.connectedDeviceId,
					success: (res) => {
						console.log('连接成功', res);
						this.currentDeviceId = deviceId;
						this.getServices(deviceId);
						uni.setBLEMTU({
							deviceId: this.connectedDeviceId,
							mtu: 32,
						})

					},
					fail: (err) => {
						console.error('连接失败', err);
					}
				});
			},

			// 获取设备服务
			getServices(deviceId) {
				let that = this;
				uni.getBLEDeviceServices({
					deviceId: this.connectedDeviceId,
					success: (res) => {
						let seAr = res.services
						seAr.forEach(v => {
							if (v.uuid.indexOf("00001000") > -1) {
								that.serviceId = v.uuid
							}
						})
						console.log(res);
						console.log('获取服务成功', res.services);
						this.getCharacteristics(deviceId, that.serviceId)
					}
				});
				//		监听蓝牙状态:包括连接异常/断开连接
				wx.onBLEConnectionStateChange(function(res) {
					console.log(res.connected)
					that.connected = res.connected;
					if (!res.connected) {
						// that.BlelinkFail();
					}
				})
			},

			// 获取特征值
			getCharacteristics(deviceId, serviceId) {
				this.serviceId = serviceId;
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: that.connectedDeviceId,
					serviceId,
					success: (res) => {
						console.log(res);
						console.log('获取特征值成功', res.characteristics);

						let chaArr = res.characteristics
						res.characteristics.forEach(v => {
							if (v.uuid.indexOf("00001002") > -1) {
								that.notifyCharacteristicsId = v.uuid
							}
							if (v.uuid.indexOf("00001001") > -1) {
								that.writeCharacteristicsId = v.uuid
							}
						})
						this.notifyBLECharacteristicValueChange(that.connectedDeviceId, serviceId, that.notifyCharacteristicsId);
					}

				});
			},

			// 启用特征值变化通知
			notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId) {
				console.log('deviceId', deviceId);
				console.log('serviceId', serviceId);
				console.log('characteristicId', characteristicId);
				uni.notifyBLECharacteristicValueChange({
					deviceId: this.connectedDeviceId,
					serviceId,
					characteristicId,
					state: true,
					success: (res) => {
						console.log('启用通知成功', res);
						// this.listenData(); // 开始监听数据
						this.writeBLECharacteristicValue('00')
					},
					fail: (err) => {
						console.log(err);
					}
				});
			},

			// 4. 监听接收数据
			listenData(characteristicId) {
				uni.onBLECharacteristicValueChange((res) => {
					let receiveText = app.buf2hex(res.value);
					that.pakInfoFun('接收数据：', receiveText)
					let str = that.hexToString(receiveText);
					if (str.length == 18) {
						let txt = str.substring(8, 17)
						console.log(txt);
					}
					if (receiveText.length == 36) {
						that.Send('03');
					}
					if (receiveText.length == 24) {
						//处理测量结果
						receiveText = that.handleResult(receiveText);
						console.log(receiveText);
						console.log(that.data.isFirst);
						if (that.data.isFirst) {
							that.setData({
								isFirst: false
							})
						} else {
							that.setData({
								receiveText: receiveText
							});
							that.saveData();
						}
					}
				});
			},

			writeBLECharacteristicValue(threeArr) {
				console.log("发送数据" + deviceId + ":" + serviceId + ":" + characteristicId)
				let val = new Uint8Array(that.SendData(threeArr));
				setTimeout(() => {
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId:that.connectedDeviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId:that.serviceId,
						// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
						characteristicId:that.notifyCharacteristicsId,
						
						// 这里的value是ArrayBuffer类型
						value: val.buffer,
						success: function(res) {
							console.log('发包成功')
							console.log(res)
						},
						fail: function(res) {
							console.log(res)
							console.log('发包失败')
							if (res.errCode === 10007) {
								console.log('尝试重新写入...');
								this.writeBLECharacteristicValue(threeArr); // 自动重试
							}
						},
						complete: function(res) {
							console.log('完成')
							console.log(res)
						}


					})
				}, 50)

			},

			//处理得出的结果
			handleResult(data) {
				let testValue1 = data.substr(18, 2);
				let testValue2 = data.substr(20, 2);
				let testValue3 = '0x' + testValue2 + testValue1;
				testValue3 = parseInt(testValue3) / 18;
				//四舍五入，保留1位小数toFixed(1)
				testValue3 = testValue3.toFixed(1);
				return testValue3
			},

			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						// return ('00' + bit.toString(16)).slice(-2)
						return parseInt(bit.toString(10));
					}
				)
				return hexArr;
			},

			//数据验证
			bccCheck(dataView) {
				let checksum = 0x00
				for (let i = 1; i < dataView.byteLength - 2; i++) {
					checksum ^= dataView.getInt8(i)
				}

				return checksum
			},



			// 5. 断开连接
			disconnect() {
				if (!this.currentDeviceId) return;

				uni.closeBLEConnection({
					deviceId: this.currentDeviceId,
					success: (res) => {
						console.log('断开连接成功', res);
						this.stopDiscovery();
					}
				});
			},

			// 停止搜索
			stopDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: (res) => {
						console.log('停止搜索成功', res);
					}
				});
			},

			// 6. 重新连接设备
			reconnect() {
				if (!this.currentDeviceId) return;

				this.connectDevice(this.currentDeviceId);
			},

		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>